package com.elasticsearch.elasticsearchapi.service;

import org.elasticsearch.client.RestHighLevelClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author ycx
 * @date 2025-05-15 15:59
 */
@Service
public class ProductService {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    //解析数据放入到es 索引中
//    public Boolean parseProduct(String keywords) throws IOException {
//        List<Product> productList = new HtmlParseUtils().parseJd(keywords);
//        //把查询到的数据添加到es中
//        BulkRequest bulkRequest = new BulkRequest();
//        bulkRequest.timeout("2m");
//        for(int i=0;i<productList.size();i++){
//            bulkRequest.add(new IndexRequest("jd_product")
//                .source(JSON.toJSONString(productList.get(i)), XContentType.JSON));
//        }
//        BulkResponse bulkResponse =restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
//        return bulkResponse.hasFailures();
//    }
//    //获取到这些数据实现搜索功能
//    public List<Map<String,Object>> searchProduct(String keywords,int pageNo,int pageSize) throws IOException {
//        if(pageNo <=1 ){
//            pageNo=pageNo+1;
//        }
//        //条件搜索
//        SearchRequest searchRequest = new SearchRequest("jd_product");
//        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();
//        //分页查询
//        sourceBuilder.from(pageNo);
//        sourceBuilder.size(pageSize);
//        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("title",keywords);
//        //精准查询
//        sourceBuilder.query(termQueryBuilder);
//        sourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
//        //执行搜索
//        searchRequest.source(sourceBuilder);
//        SearchResponse searchResponse =restHighLevelClient.search(searchRequest,RequestOptions.DEFAULT);
//        //解析结果
//        List<Map<String,Object>> productList=new ArrayList<>();
//        for (SearchHit searchHits:searchResponse.getHits().getHits()) {
//            productList.add(searchHits.getSourceAsMap());
//        }
//        return productList;
//    }
}
